package jobs;

import com.google.gson.Gson;
import models.crawlers.CrawlerEventObserver;
import models.crawlers.common.ShopCrawler;
import models.crawlers.common.WebSiteInfo;
import models.entities.CrawlerEntity;
import play.Logger;
import play.jobs.Job;

import java.io.Serializable;

public class CrawlerJob extends Job implements Serializable {
    private ShopCrawler crawler;
    private String dataPath;
    private CrawlerEntity crawlerInfo;

    public CrawlerJob(String dataPath, ShopCrawler crawler, CrawlerEntity crawlerEntity) {
        this.dataPath = dataPath;
        this.crawler = crawler;
        this.crawlerInfo = crawlerEntity;
    }

    public void doJob() {
        if (crawler.suspended)
            return;
        crawler.addObserver(new CrawlerEventObserver(crawlerInfo, dataPath));
        try {
            if (crawlerInfo.webSiteInfo != null) {
                Gson gson = new Gson();
                WebSiteInfo webSiteInfo = gson.fromJson(crawlerInfo.webSiteInfo, WebSiteInfo.class);
                if (crawlerInfo.status == CrawlerEntity.CrawlerStatuses.Completed)
                    crawler.start();
                else
                    crawler.start(webSiteInfo);
            } else {
                crawler.start();
            }
        } catch (Exception e) {
            e.printStackTrace();
            Logger.error(e, "Crawler start error");
        }
    }

    public void stopCrawler() {
        if (crawler != null) {
            crawler.stop();
        }
    }

}
